<template>
  <div class="audio-device-test">
    <h3>Audio Device Management Test</h3>
    
    <div class="section">
      <h4>Basic Audio Devices</h4>
      <n-button @click="loadBasicDevices" :loading="loading">Load Basic Devices</n-button>
      
      <div v-if="basicDevices" class="device-list">
        <div class="device-group">
          <h5>Input Devices ({{ basicDevices.input_devices.length }})</h5>
          <div v-for="device in basicDevices.input_devices" :key="device.id" class="device-item">
            <span>{{ device.name }}</span>
            <span class="device-id">{{ device.id }}</span>
            <n-tag v-if="device.is_default" type="success" size="small">Default</n-tag>
            <n-button size="small" @click="selectInputDevice(device.id)">Select</n-button>
          </div>
        </div>
        
        <div class="device-group">
          <h5>Output Devices ({{ basicDevices.output_devices.length }})</h5>
          <div v-for="device in basicDevices.output_devices" :key="device.id" class="device-item">
            <span>{{ device.name }}</span>
            <span class="device-id">{{ device.id }}</span>
            <n-tag v-if="device.is_default" type="success" size="small">Default</n-tag>
            <n-button size="small" @click="selectOutputDevice(device.id)">Select</n-button>
          </div>
        </div>
      </div>
    </div>

    <div class="section">
      <h4>Detailed Audio Devices</h4>
      <n-button @click="loadDetailedDevices" :loading="loadingDetailed">Load Detailed Devices</n-button>
      
      <div v-if="detailedDevices.length > 0" class="device-list">
        <div v-for="device in detailedDevices" :key="device.id" class="detailed-device-item">
          <h6>{{ device.name }} ({{ device.id }})</h6>
          <n-tag v-if="device.is_default" type="success" size="small">Default</n-tag>
          <div class="device-specs">
            <div>Sample Rates: {{ device.supported_sample_rates.join(', ') }} Hz</div>
            <div>Channels: {{ device.supported_channels.join(', ') }}</div>
            <div>Formats: {{ device.supported_formats.join(', ') }}</div>
          </div>
        </div>
      </div>
    </div>

    <div class="section">
      <h4>Audio Levels</h4>
      <n-button @click="getAudioLevels" :loading="loadingLevels">Get Audio Levels</n-button>
      
      <div v-if="audioLevels" class="levels">
        <div>Input Level: {{ (audioLevels.input_level * 100).toFixed(1) }}%</div>
        <div>Output Level: {{ (audioLevels.output_level * 100).toFixed(1) }}%</div>
        <div>Muted: {{ audioLevels.is_muted ? 'Yes' : 'No' }}</div>
      </div>
    </div>

    <div class="section">
      <h4>Stream Configuration</h4>
      <div class="config-form">
        <n-form-item label="Sample Rate">
          <n-input-number v-model:value="streamConfig.sample_rate" :min="8000" :max="192000" />
        </n-form-item>
        <n-form-item label="Channels">
          <n-input-number v-model:value="streamConfig.channels" :min="1" :max="8" />
        </n-form-item>
        <n-form-item label="Buffer Size">
          <n-input-number v-model:value="streamConfig.buffer_size" :min="64" :max="8192" />
        </n-form-item>
        <n-form-item label="Format">
          <n-select v-model:value="streamConfig.format" :options="formatOptions" />
        </n-form-item>
        <n-button @click="updateStreamConfig" :loading="loadingConfig">Update Config</n-button>
      </div>
    </div>

    <div v-if="error" class="error">
      <n-alert type="error" :title="error" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { NButton, NTag, NAlert, NFormItem, NInputNumber, NSelect } from 'naive-ui'
import { 
  getAudioDevices, 
  setAudioDevice, 
  getAudioLevels as getAudioLevelsApi,
  getDetailedAudioDevices,
  setAudioStreamConfig,
  getAudioStreamConfig
} from '../services/tauri-api'
import type { AudioDevices, AudioLevels, AudioDeviceInfo, AudioStreamConfig } from '../types'

const loading = ref(false)
const loadingDetailed = ref(false)
const loadingLevels = ref(false)
const loadingConfig = ref(false)
const error = ref<string | null>(null)

const basicDevices = ref<AudioDevices | null>(null)
const detailedDevices = ref<AudioDeviceInfo[]>([])
const audioLevels = ref<AudioLevels | null>(null)
const streamConfig = ref<AudioStreamConfig>({
  sample_rate: 48000,
  channels: 1,
  buffer_size: 1024,
  format: 'f32'
})

const formatOptions = [
  { label: 'f32', value: 'f32' },
  { label: 'i16', value: 'i16' },
  { label: 'i32', value: 'i32' },
  { label: 'u16', value: 'u16' }
]

const loadBasicDevices = async () => {
  loading.value = true
  error.value = null
  try {
    basicDevices.value = await getAudioDevices()
  } catch (e) {
    error.value = `Failed to load basic devices: ${e}`
  } finally {
    loading.value = false
  }
}

const loadDetailedDevices = async () => {
  loadingDetailed.value = true
  error.value = null
  try {
    detailedDevices.value = await getDetailedAudioDevices()
  } catch (e) {
    error.value = `Failed to load detailed devices: ${e}`
  } finally {
    loadingDetailed.value = false
  }
}

const selectInputDevice = async (deviceId: string) => {
  try {
    await setAudioDevice(deviceId, undefined)
    await loadBasicDevices() // Refresh to show current selection
  } catch (e) {
    error.value = `Failed to select input device: ${e}`
  }
}

const selectOutputDevice = async (deviceId: string) => {
  try {
    await setAudioDevice(undefined, deviceId)
    await loadBasicDevices() // Refresh to show current selection
  } catch (e) {
    error.value = `Failed to select output device: ${e}`
  }
}

const getAudioLevels = async () => {
  loadingLevels.value = true
  error.value = null
  try {
    audioLevels.value = await getAudioLevelsApi()
  } catch (e) {
    error.value = `Failed to get audio levels: ${e}`
  } finally {
    loadingLevels.value = false
  }
}

const updateStreamConfig = async () => {
  loadingConfig.value = true
  error.value = null
  try {
    await setAudioStreamConfig(streamConfig.value)
    // Verify the config was set
    const currentConfig = await getAudioStreamConfig()
    streamConfig.value = currentConfig
  } catch (e) {
    error.value = `Failed to update stream config: ${e}`
  } finally {
    loadingConfig.value = false
  }
}

// Load initial config
const loadInitialConfig = async () => {
  try {
    streamConfig.value = await getAudioStreamConfig()
  } catch (e) {
    console.warn('Failed to load initial stream config:', e)
  }
}

loadInitialConfig()
</script>

<style scoped>
.audio-device-test {
  padding: 20px;
  max-width: 800px;
}

.section {
  margin-bottom: 30px;
  padding: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
}

.device-list {
  margin-top: 15px;
}

.device-group {
  margin-bottom: 20px;
}

.device-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  margin-bottom: 5px;
}

.device-id {
  font-family: monospace;
  font-size: 0.8em;
  color: #666;
}

.detailed-device-item {
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}

.device-specs {
  margin-top: 8px;
  font-size: 0.9em;
  color: #666;
}

.device-specs > div {
  margin-bottom: 4px;
}

.levels {
  margin-top: 15px;
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.levels > div {
  margin-bottom: 5px;
}

.config-form {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
  margin-top: 15px;
}

.config-form .n-form-item {
  margin-bottom: 0;
}

.error {
  margin-top: 20px;
}
</style>